const express = require('express')
const { query } = require('../utils/pool')
const router = express.Router()
// 用户列表
router.get('/list', async (req, res, next) => {
  const obj = req.query;
  if (!obj.pno) obj.pno = 1;
  if (!obj.count) obj.count = 10;
  const size = parseInt(obj.count);
  const start = (obj.pno - 1) * size;
  try {
    let sql
    if (obj.name || obj.sex) {
      if (obj.name) {
        sql = `select * from ih_user where name like '%${obj.name}%' limit ?,?;select count(*) as n from ih_user where name like '%${obj.name}%'`
      } else if (obj.sex) {
        sql = `select * from ih_user where sex=${obj.sex} limit ?,?;select count(*) as n from ih_user where sex=${obj.sex}`
      } else {
        sql = `select * from ih_user where name like '%${obj.name}%' and sex=${obj.sex} limit ?,?;select count(*) as n from ih_user where name like '%${obj.name}%' and sex=${obj.sex}`
      }
    } else {
      sql = 'select * from ih_user limit ?,?;select count(*) as n from ih_user'
    }
    console.log(sql)
    var result = await query(
      sql,
      [start, size]
    )
  } catch (err) {
    return next(err)
  };
  console.log(result);
  res.send({
    code: 200,
    msg: '用户列表',
    data: result[0],
    total: result[1][0].n,
    pno: obj.pno
  });
})

// 个人信息
router.get('/detail', async (req, res, next) => {
  const { id } = req.query
  try {
    var result = await query('select * from ih_user where id=?;select * from ih_health where user_id=?', [id, id])
  } catch (err) {
    return next(err)
  }
  res.send({
    code: 200,
    msg: '个人信息',
    data: { ...result[0][0], health: result[1] }
  })
})

module.exports = router